package top.lywivan.reggie.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.Constants;
import com.itheima.reggie.common.SecurityContext;
import com.itheima.reggie.entity.*;
import top.lywivan.reggie.exception.BusinessException;
import top.lywivan.reggie.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.lywivan.reggie.service.ShoppingCartService;
import top.lywivan.reggie.service.UserService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Override
    @Transactional
    public void saveWithOrderDetail(Orders orders) {
        //获取当前登陆的用户id
        Long userId = SecurityContext.getUserId();
        orders.setStatus(Constants.ORDER_STATUS_WAIT_PAY);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        BigDecimal amount=new BigDecimal(0);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(Wrappers.<ShoppingCart>lambdaQuery().eq(ShoppingCart::getUserId, userId));
        //健壮性判断，避免postman直接发送请求
        if (shoppingCartList.size()==0){
            throw new BusinessException("购物车为空！");
        }
        for (ShoppingCart shoppingCart : shoppingCartList) {
            BigDecimal price = getPrice(shoppingCart);
            Integer number = shoppingCart.getNumber();
            amount = amount.add(price.multiply(new BigDecimal(number)));
        }
        orders.setAmount(amount);
        //以下字段为冗余字段，用于提高查询效率
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        userService.update(Wrappers.<User>lambdaUpdate().set(User::getName,addressBook.getConsignee()).eq(User::getId,userId));
        User user = userService.getById(userId);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        //闲的没事，设置下number
        long id = IdWorker.getId();
        orders.setNumber(id+"");
        orders.setId(id);
        this.save(orders);
        //下面保存订单的明细
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            //设置对应的订单id
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(orderDetailList);
        //提交完成订单后，需要清空购物车
        shoppingCartService.remove(Wrappers.<ShoppingCart>lambdaQuery()
                .eq(ShoppingCart::getUserId,SecurityContext.getUserId()));
    }

    @Override
    public void saveAgain(Orders orders) {
        Long userId = SecurityContext.getUserId();
        //先清空原有购物车
        shoppingCartService.remove(Wrappers.<ShoppingCart>lambdaQuery().eq(ShoppingCart::getUserId,userId));
        List<OrderDetail> orderDetailList = orderDetailService.list(Wrappers.<OrderDetail>lambdaQuery().eq(OrderDetail::getOrderId, orders.getId()));
        orderDetailList.forEach(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setId(null);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
        });
    }

    private BigDecimal getPrice(ShoppingCart shoppingCart){
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        if (dishId!=null){
            return dishService.getById(dishId).getPrice();
        }else {
            return setmealService.getById(setmealId).getPrice();
        }
    }
}